﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service.Service {
    public class TokenInfoService : ServiceBase, ITokenService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        public TokenInfoService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            this._iUnitOfWork = iUnitOfWork;
        }
        public token_info_dto Get(long id, out bool pool) {
            pool = false;
            try {
                pool = true;
                var key = SecureHelper.MD5("TokenInfo" + id);
                var obj = _iUnitOfWork.GetCache<token_info_dto>(key);
                if (obj != null) return obj;
                var model = context.TokenInfo.Find(id);

                if (model == null) return null;
                var result = new token_info_dto { access_token = model.AccessToken, expires_date = model.ExpiresDate.ToDateTime(), expires_in = model.ExpiresIn, id = model.Id };
                _iUnitOfWork.SetCache(key, result);
                return result;
            } catch {
                pool = false;
                return null;
            }
        }

        public int Save(token_info_dto dto) {
            var model = context.TokenInfo.FirstOrDefault(c => c.Id == dto.id);
            var ext = model == null;
            string key = string.Empty;
            if (ext) {
                model = new TokenInfo();
            } else
                key = SecureHelper.MD5("TokenInfo" + dto.id);
            model.Id = dto.id;
            model.AccessToken = dto.access_token;
            model.ExpiresDate = dto.expires_date.ToUnix();
            model.ExpiresIn = dto.expires_in;
            if (ext) {
                context.TokenInfo.Add(model);
            }

            int result = _iUnitOfWork.Commit();
            if (result > 0 && !string.IsNullOrEmpty(key))
                _iUnitOfWork.RomoveCache(key);

            return result;
        }

    }
}
